/**
 *@描述：部门管理
 *@作者：顾云飞
 *@创建时间：2023/1/17
 *@最后修改时间：2023/1/18
 */
import {
  EllipsisOutlined,
  PlusOutlined,
  SearchOutlined,
  SyncOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Table, Space, Popconfirm, Button, message, Tag, Card, Form, Input } from 'antd';
import { queryOfficeList, DeleteOfficeRequest } from '@/pages/Dashboard/System/Office/service';
import { GetOfficeListRequestParams } from './data';
import { useRef, useState, useEffect } from 'react';
import type { ColumnsType } from 'antd/es/table';

import OfficeFormModal from './OfficeFormModal';
interface OfficeItem {
  id: string;
  name: string;
  type: string;
}

const OfficeList = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [showOfficeModal, setShowOfficeModal] = useState<boolean>(false);
  const [officeFormValues, setOfficeFormValues] = useState({});
  const [parentOfficeId, setParentOfficeId] = useState(''); // 弹窗的父级部门的id

  const columns: ColumnsType<OfficeItem> = [
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
      width: 160,
    },
    {
      title: '部门类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (_, record) => (
        <Space>
          <Tag color={record.type === '1' ? 'success' : 'default'} key={record.type}>
            {record.type === '1' ? '显示' : '禁用'}
          </Tag>
        </Space>
      ),
    },
    {
      title: '级别',
      dataIndex: 'grade',
      key: 'grade',
      width: 160,
    },
    {
      title: '操作',
      key: 'operation',
      width: 160,
      render: (_, record) => [
        record.type !== 'BUTTON' && record.type !== 'EXTLINK' && (
          <Button
            type="link"
            size="small"
            onClick={() => {
              setShowOfficeModal(true);
              setParentOfficeId(record.id);
            }}
          >
            新增
          </Button>
        ),
        <Button
          type="link"
          onClick={() => {
            setShowOfficeModal(true);
            setOfficeFormValues(record);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          title="确认删除吗？"
          okText="确定"
          cancelText="取消"
          onConfirm={() => delOffice(record.id)}
        >
          <Button
            // className={styles.removeBtn}
            size="small"
            type="link"
            danger
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  //组件初始化函数
  //todo: useEffect函数
  useEffect(() => {
    getOfficeList({});
  }, []);
  //查询列表，可通过菜单名称查询
  const getOfficeList = async ({ keyword }: { keyword?: string }) => {
    setLoading(true);
    const requestParams: GetOfficeListRequestParams = {
      keyword: keyword,
    };
    // console.log(requestParams);
    const res = await queryOfficeList(requestParams);
    if (res.code == 200) {
      setData(res.data);
    }
    setLoading(false);
  };
  //根据部门ID，删除部门，调用DeleteOfficeRequest接口
  //todo: 删除部门
  const delOffice = async (id?: string) => {
    setLoading(true);
    const res = await DeleteOfficeRequest({
      ids: id,
    });
    if (res.code == 200) {
      setLoading(false);
      actionRef?.current?.reload();
      message.success('删除成功！');
    } else {
      setLoading(false);
      message.error('删除失败！');
    }
  };
  //添加人员成功触发的函数
  //todo: onSuccess
  const onSuccess = async () => {
    getOfficeList({});
  };
  const onCancel = () => {
    setShowOfficeModal(false);
    setOfficeFormValues({});
  };
  // 选择
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  return (
    <div>
      <Card style={{ marginBottom: '20px' }}>
        <Form layout="inline">
          <Form.Item label="部门名称">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button type="default" icon={<SyncOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card
        title={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setShowOfficeModal(true);
                setParentOfficeId('1');
              }}
            >
              新增
            </Button>
            <Button
              type="primary"
              icon={<DeleteOutlined />}
              danger
              disabled={selectedRowKeys.length === 0}
              onClick={() => {
                delOffice(selectedRowKeys.toString());
              }}
            >
              批量删除
            </Button>
          </Space>
        }
      >
        {data.length && (
          <Table
            dataSource={data}
            defaultExpandAllRows={true}
            columns={columns}
            rowSelection={{
              selectedRowKeys,
              onChange: onSelectChange,
            }}
            loading={loading}
            rowKey="id"
            size="small"
            //  scroll={{ y: 250 }}
            pagination={false}
          />
        )}
      </Card>
      {(officeFormValues && Object.keys(officeFormValues).length) || showOfficeModal ? (
        <OfficeFormModal
          parentOfficeId={parentOfficeId}
          officeFormValues={officeFormValues}
          onSuccess={onSuccess}
          show={showOfficeModal}
          onCancel={onCancel}
        ></OfficeFormModal>
      ) : null}
    </div>
  );
};
export default OfficeList;
